/* eslint-disable no-dupe-class-members */
/* eslint-disable indent */
'use strict'

const Service = require('egg').Service
const dayjs = require('dayjs')
const { Op } = require('sequelize')

// 信息要返回的字段
const attributes = ['id', 'barcode', 'barname', 'expires', 'version', 'status', 'logged_at']

class PlaceService extends Service {

    // 查询所有门店列表
    async getPlaceList(params) {
        const { model, helper } = this.ctx
        const currentPage = params?.pageIndex ?? 1
        const pageSize = params?.pageSize ?? 50
        const where = {}
        if (params.barname) {
            where.barname = {
                [Op.like]: `%${params.barname}%`
            }
        }
        if (params.status !== undefined && params.status != null) {
            where.status = params.status
        }

        return await model.Place.findAndCountAll({
            where,
            offset: (currentPage - 1) * pageSize, // 计算分页偏移量
            limit: pageSize,
            attributes
        })
            .then(async result => {
                if (result) {
                    return {
                        list: result.rows,
                        total: result.count
                    }
                }
                helper.failed(1008, null, '查询门店列表失败')
                return false
            })
            .catch(async error => {
                helper.failed(1001, null, error.errors[0]?.message)
                return false
            })
    }

    // 新增门店
    async createPlace(params) {
        const { model, helper, logger } = this.ctx
        const { barcode, barname, expires } = params
        const version = params?.version || '0.0.0.0'
        return await model.Place.create({
            barcode,
            barname,
            expires: dayjs(expires).format('YYYY-MM-DD HH:mm:ss'),
            created_at: dayjs().format('YYYY-MM-DD HH:mm:ss'),
            updated_at: dayjs().format('YYYY-MM-DD HH:mm:ss'),
            version
        })
            .then(async data => {
                if (data) {
                    return data
                }
                helper.failed(1005, null, '新增门店失败')
                return false
            })
            .catch(async error => {
                if (error?.original?.sqlMessage) {
                    logger.error(`新增门店失败   barcode:[${barcode}]   ${error?.original?.sqlMessage}`)
                    helper.failed(1001, null, error?.original?.sqlMessage)
                } else if (error?.errors[0]?.message) {
                    logger.error(`新增门店失败   barcode:[${barcode}]    ${error.errors[0]?.message}`)
                    helper.failed(1001, null, error.errors[0]?.message)
                } else {
                    logger.error(`新增门店失败   barcode:[${barcode}]   ${JSON.stringify(error)}`)
                    helper.failed(1001, null, JSON.stringify(error))
                }
                return false
            })
    }

    // 编辑门店
    async editPlace(params) {
        const { model, helper, logger } = this.ctx

        return await model.Place.findByPk(params.id)
            .then(async result => {
                if (result) {
                    return await result.update(params)
                        .then(async data => {
                            if (data) {
                                return data
                            }
                            helper.failed(1006, null, '编辑门店失败')
                            return false
                        })
                        .catch(async error => {
                            if (error?.original?.sqlMessage) {
                                logger.error(`编辑门店失败   id:[${params.id}]   ${error?.original?.sqlMessage}`)
                                helper.failed(1001, null, error?.original?.sqlMessage)
                            } else if (error?.errors[0]?.message) {
                                logger.error(`编辑门店失败   id:[${params.id}]    ${error.errors[0]?.message}`)
                                helper.failed(1001, null, error.errors[0]?.message)
                            } else {
                                logger.error(`编辑门店失败   id:[${params.id}]   ${JSON.stringify(error)}`)
                                helper.failed(1001, null, JSON.stringify(error))
                            }
                            return false
                        })
                }
                helper.failed(1004, null, '门店不存在')
                return false
            })
            .catch(async error => {
                if (error?.original?.sqlMessage) {
                    logger.error(`编辑查询门店失败   id:[${params.id}]   ${error?.original?.sqlMessage}`)
                    helper.failed(1001, null, error?.original?.sqlMessage)
                } else if (error?.errors[0]?.message) {
                    logger.error(`编辑查询门店失败   id:[${params.id}]    ${error.errors[0]?.message}`)
                    helper.failed(1001, null, error.errors[0]?.message)
                } else {
                    logger.error(`编辑查询门店失败   id:[${params.id}]   ${JSON.stringify(error)}`)
                    helper.failed(1001, null, JSON.stringify(error))
                }
                return false
            })
    }

    // 删除门店
    async deletePlace(params) {
        const { model, helper, logger } = this.ctx

        return await model.Place.findByPk(params.id)
            .then(async result => {
                if (result) {
                    return await result.destroy()
                        .then(async data => {
                            if (data) {
                                return data
                            }
                            helper.failed(1007, null, '删除门店失败')
                            return false
                        })
                        .catch(async error => {
                            if (error?.original?.sqlMessage) {
                                logger.error(`删除门店失败   id:[${params.id}]   ${error?.original?.sqlMessage}`)
                                helper.failed(1001, null, error?.original?.sqlMessage)
                            } else if (error?.errors[0]?.message) {
                                logger.error(`删除门店失败   id:[${params.id}]    ${error.errors[0]?.message}`)
                                helper.failed(1001, null, error.errors[0]?.message)
                            } else {
                                logger.error(`删除门店失败   id:[${params.id}]   ${JSON.stringify(error)}`)
                                helper.failed(1001, null, JSON.stringify(error))
                            }
                            return false
                        })
                }
                helper.failed(1004, null, '门店不存在')
                return false
            })
            .catch(async error => {
                if (error?.original?.sqlMessage) {
                    logger.error(`删除查询门店失败   id:[${params.id}]   ${error?.original?.sqlMessage}`)
                    helper.failed(1001, null, error?.original?.sqlMessage)
                } else if (error?.errors[0]?.message) {
                    logger.error(`删除查询门店失败   id:[${params.id}]    ${error.errors[0]?.message}`)
                    helper.failed(1001, null, error.errors[0]?.message)
                } else {
                    logger.error(`删除查询门店失败   id:[${params.id}]   ${JSON.stringify(error)}`)
                    helper.failed(1001, null, JSON.stringify(error))
                }
                return false
            })
    }

    // 请求门店授权信息
    async authPlace(params) {
        const { model, helper, logger } = this.ctx
        const { barcode, barname } = params

        const where = {
            barcode
        }
        return await model.Place.findOne({ where })
            .then(async result => {
                const logged_at = dayjs().format('YYYY-MM-DD HH:mm:ss')
                params.logged_at = logged_at
                params.version = params?.version || '0.0.0.0'
                if (result) {
                    if (result.status === 1) {
                        await result.update(params, { where: { id: result.id } })
                        const data = result.toJSON()
                        data.logged_at = logged_at
                        return result
                    }
                    helper.failed(2002, null, '门店已停用')
                    return false
                }
                // 自动生成门店信息，并设置1个月试用期
                const placeInfo = await this.createPlace({ barcode, barname, expires: dayjs().add(30, 'day').format('YYYY-MM-DD HH:mm:ss') })
                if (placeInfo) {
                    return placeInfo
                }
                helper.failed(1005, null, '增加使用门店失败')
                return false
            })
            .catch(async error => {
                if (error?.original?.sqlMessage) {
                    logger.error(`请求门店授权店失败   barcode:[${barcode}]   ${error?.original?.sqlMessage}`)
                    helper.failed(1001, null, error?.original?.sqlMessage)
                } else if (error?.errors[0]?.message) {
                    logger.error(`请求门店授权店失败   barcode:[${barcode}]    ${error.errors[0]?.message}`)
                    helper.failed(1001, null, error.errors[0]?.message)
                } else {
                    logger.error(`请求门店授权店失败   barcode:[${barcode}]   ${JSON.stringify(error)}`)
                    helper.failed(1001, null, JSON.stringify(error))
                }
                return false
            })
    }

    // 根据barcode查询门店信息
    async getPlaceByBarcode(params) {
        const { model, helper, logger } = this.ctx

        const where = {
            barcode: params.barcode
        }
        return await model.Place.findOne({
            where,
            // eslint-disable-next-line array-bracket-spacing
            attributes: ['id', 'barcode', 'barname', 'version', 'expires']
        })
            .then(async result => {
                if (result) {
                    return result
                }
                helper.failed(1004, null, '门店不存在')
                return false
            })
            .catch(async error => {
                if (error?.original?.sqlMessage) {
                    logger.error(`查询门店失败   barcode:[${params.barcode}]   ${error?.original?.sqlMessage}`)
                    helper.failed(1001, null, error?.original?.sqlMessage)
                } else if (error?.errors[0]?.message) {
                    logger.error(`查询门店失败   barcode:[${params.barcode}]    ${error.errors[0]?.message}`)
                    helper.failed(1001, null, error.errors[0]?.message)
                } else {
                    logger.error(`查询门店失败   barcode:[${params.barcode}]   ${JSON.stringify(error)}`)
                    helper.failed(1001, null, JSON.stringify(error))
                }
                return false
            })

    }
}

module.exports = PlaceService
